import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_HTTP + process.env.VUE_APP_BASE_API, // url = base url + request url
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 20000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    if (config.third) {
      config.url = '/' + config.third + config.url
    } else {
      config.url = '/trade/wx/noCheck' + config.url
    }
    console.log(config.url)
    console.log(process.env.VUE_APP_BASE_HTTP + process.env.VUE_APP_BASE_API)
    // do something before request is sent
    if (store.getters.token) {
      config.headers['Authorization'] = 'Bearer ' + getToken()
    }
    if (store.getters.token === 'admin-token') {
      store.dispatch('user/resetToken')
    }
    if (config.version === 'v2') {
        config.headers['content-Type'] = 'application/json;charset=utf-8;'
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data
    if (res.code) {
      res.code = res.code * 1
    }
    if (res.code !== 0 && res.code) {
      if (process.env.ENV === 'development') {
        Message({
          message: res.msg || 'error',
          type: 'error',
          duration: 5 * 1000
        })
      }
      return Promise.reject(res.message || 'error')
    } else {
      return res
    }
  },
  error => {
    if (error.response.data.code * 1 === 401) {
      MessageBox.confirm(error.response.data.message, ' ', {
        confirmButtonText: '重新登录',
        cancelButtonText: '关闭',
        type: 'warning'
      }).then(() => {
        store.dispatch('user/resetToken').then(() => {
          location.reload()
        })
      })
      // 加提示
      return false
    }
    console.log('err' + error) // for debug
    Message({
      message: error.response.data.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
